//全局客户类型(1:公众;2:政企)
var g_custType = "1";
//数据日期
var g_dataDate = "20191231"
//全局渠道信息
var g_channelInfo = {};
var g_channelCode = "";
var g_channelName = "";


//门店基本信息
function loadChannelBaseInfo() {
    fetch('/random_forest_params')
        .then(res => res.json())
        .then(res => {
            document.getElementById('base-info').innerHTML = `
                <div style="color: white; font-size: 2rem; margin-top: 30px;">
                    <div>
                        决策树数量：${res.n_estimators}
                    </div>
                    <div>
                        随机种子：${res.random_state}
                    </div>
                    <div>
                        节点最小样本：${res.min_samples_split}
                    </div>
                    <div>
                        叶节点最小样本：${res.min_samples_leaf}
                    </div>
                    <div>
                        决策树采样：${res.bootstrap ? '开启' : '关闭'}
                    </div>
                </div>
            `
        })
}

//门店受理详情
function loadChannelHandleDetail(data, time) {
    var option = {
        tooltip: {trigger: 'axis', axisPointer: {lineStyle: {color: '#fff'}}},
        legend: {
            icon: 'rect',
            itemWidth: 14, itemHeight: 5, itemGap: 10,
            data: ['总请求数', '正常请求数', '异常请求数'],
            right: '10px', top: '0px',
            textStyle: {fontSize: 12, color: '#fff'}
        },
        grid: {x: 40, y: 50, x2: 45, y2: 40},
        xAxis: [{
            type: 'category',
            boundaryGap: false,
            axisLine: {lineStyle: {color: '#57617B'}},
            axisLabel: {textStyle: {color: '#fff'}},
            data: time
        }],
        yAxis: [{
            type: 'value',
            axisTick: {
                show: false
            },
            axisLine: {lineStyle: {color: '#57617B'}},
            axisLabel: {margin: 10, textStyle: {fontSize: 12}, textStyle: {color: '#fff'}, formatter: '{value}'},
            splitLine: {lineStyle: {color: '#57617B'}}
        }],
        series: [{
            name: '总请求数', type: 'line', lineStyle: {normal: {width: 2}},
            yAxisIndex: 0,
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(3, 194, 236, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(3, 194, 236, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {normal: {color: '#03C2EC'}},
            data: data.total
        }, {
            name: '正常请求数', type: 'line', lineStyle: {normal: {width: 2}},
            yAxisIndex: 0,
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(218, 57, 20, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(218, 57, 20, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {normal: {color: '#DA3914'}},
            data: data.normal
        }, {
            name: '异常请求数', type: 'line', lineStyle: {normal: {width: 2}},
            yAxisIndex: 0,
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(232, 190, 49, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(232, 190, 49, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {normal: {color: '#E8BE31'}},
            data: data.anomalous
        }]
    };
    var myChart = echarts.init(document.getElementById('channel_handle_detail'));
    // myChart.clear();
    myChart.setOption(option);
    // if (data.handleTimeData.length > 0) {
    //     myChart.setOption(option);
    // } else {
    //     noDataTip($("#channel_handle_detail"));
    // }
}


//加载营业员受理详情
function loadStaffHandleDetail(data) {
    fetch('/model_performance?type=1')
        .then(res => res.json())
        .then(res => {
            let list = ''
            res.data.map((item, index) => {
                list = list + `
                    <div>
                        <div>${Object.keys(item).map(key => `<div style="line-height: 3rem">${key}: ${item[key]}</div>`).join('')}</div>
                    </div>
                `
            })
            document.getElementById('staff-info').innerHTML = list
        })
}

//加载门店台席健康度详情
function loadChannelDeviceDetail() {
    let progressLen=314;
    const c1 = document.getElementById('c1');
    const c2 = document.getElementById('c2')

    function setPercent(num1, num2){
        c1.style['stroke-dashoffset']=progressLen-(progressLen/100)*num1;
        c2.style['stroke-dashoffset']=progressLen-(progressLen/100)*num2;
    }
    setInterval(() => {
        fetch('/system_metrics')
            .then(res => res.json())
            .then(res => {
                let up = res.上行带宽速率.split(" ")[0]
                let down = res.下行带宽速率.split(" ")[0]
                let all = res.总带宽速率.split(" ")[0]

                document.getElementById('up').innerText = res.上行带宽速率
                document.getElementById('down').innerText = res.下行带宽速率
                document.getElementById('all').innerText = res.总带宽速率
                document.getElementById('all_m').innerText = res.总内存
                document.getElementById('cpu').innerHTML = res.CPU使用率
                document.getElementById('me').innerHTML = res.内存使用率
                document.getElementById('use_me').innerText = res.已使用内存

                document.getElementById('up_row').style.width = `${Number(up) / Number(all) * 100}%`
                document.getElementById('down_row').style.width = `${Number(down) / Number(all) * 100}%`
                document.getElementById('use_me_row').style.width = res.内存使用率
                setPercent(res.CPU使用率.split("%")[0], res.内存使用率.split("%")[0])
            })
    }, 1000)
}

//加载业务类型耗时详情
function loadBusinessTypeTimeDetail(data) {
    fetch('dataset_info')
        .then(res => res.json())
        .then(res => {
            let list = ''
            for (let key in res) {
                if (res.hasOwnProperty(key)) { // 确保是对象自有属性，不是原型链上的属性
                    list = list + `
                        <div>
                            <div style="padding: 10px; border-radius: 10px; background: #ffffff10; line-height: 3rem;">
                                ${key}：
                                <div>
                                    <div>${res[key].大小 ? '大小：' + res[key].大小 : ''}</div>
                                    <div>${res[key].数量 ? '数量：' + res[key].数量 : ''}</div>
                                </div>
                            </div>
                        </div>
                    `
                }
            }
            document.getElementById('business-type-time-detial').innerHTML = list
        })
}


//初始化基础信息
function initBaseInfo() {
    //初始化日期
    /*$("#data-date").my97({
       dateFmt:'yyyyMMdd',
       minDate:"%y-{%M}-{%d-30}",
       maxDate:"%y-%M-{%d}",
       startDate: [{
           doubleCalendar: false,
           isShowWeek: false,
           isShowClear: false,
           readOnly: true
       }],
       onpicked:function(dp){
           g_dataDate=$('#data-date').val();
           $("#query-page-data").trigger("click");
       }
   });*/
    var dataDate = new Date().format("yyyy年MM月dd日");
    $("#td-data-date").text(dataDate);


    $(".cust-type-default").on("click", function () {
        $(this).addClass("active").siblings().removeClass("active");
        g_custType = $(this).attr("type");
        $("#query-page-data").trigger("click");
    });

}

//获取渠道参数
function getGroupChannelParam() {
    var areaCode = "";
    try {
        var cityId = $('#selectCity').combobox("getValue");
        var countyId = $('#selectCounty').combobox("getValue");
        if ("" == areaCode && "" != countyId) {
            areaCode = countyId;
        } else if ("" == areaCode && "" != cityId) {
            areaCode = cityId;
        }
    } catch (e) {
    }
    var channelName = $.trim($("#channel_name").val());
    var channelParam = {'areaCode': areaCode, "channelName": channelName};
    return channelParam;
}


function noDataTip($selector) {
    var currModH = $selector.height();
    var top = currModH > 180 ? "35%" : "13%";
    var $li = [
        "<div class='no-data' style='width:90%;position: absolute;top:" + top + ";text-align:center;color:#a59999;'>",
        "<img src='../static/images/no-data.png' style='width:200px;height:200px;'/>",
        "<div style='font-size:16px;opacity:0.7;color:#fff;'>暂无数据</div>",
        "</div>"
    ]
    $selector.append($li.join(""));
}

function keepTwoDecimal(currVal) {
    var result = parseFloat(currVal);
    if (isNaN(result)) {
        return false;
    }
    result = Math.round(currVal * 100) / 100;
    return result;
}

function loadData() {
    var ws = new WebSocket("wss://echo.websocket.org");

    ws.onopen = function(evt) {
      console.log("Connection open ...");
      ws.send("Hello WebSockets!");
    };

    ws.onmessage = function(evt) {
      console.log( "Received Message: " + evt.data);

    };
}

//初始化页面
function loadPageData() {
    //获取渠道信息
    var groupChannelInfo = g_channelInfo;
    //第一步：优先判断url请求参数里面
    let param = JSON.parse(gDataGather.param);
    if (Object.keys(param).length > 0) {
        groupChannelInfo = param;
        gDataGather.param = "{}";
    }
    if (Object.keys(groupChannelInfo).length == 0) {
        groupChannelInfo = window.localStorage.getItem("group-channel-info");
        if (undefined == groupChannelInfo || null == groupChannelInfo) {
            groupChannelInfo = {
                "channelCode": "11228790",
                "groupChannelCode": "3201001965930",
                "channelName": "中国电信南京分公司@玄武大钟亭营业厅"
            };
        } else {
            groupChannelInfo = JSON.parse(groupChannelInfo);
        }
    } else {
        window.localStorage.setItem("group-channel-info", JSON.stringify(groupChannelInfo));
    }
    //设置全局渠道编码、渠道名称
    g_channelCode = groupChannelInfo.channelCode;
    g_channelName = groupChannelInfo.channelName;
    //开始动画特效
    $('#load').show();
    $('#load').fadeOut(500, function () {
    });

    function getTime(time, s) {
        return new Date(time.getTime() - (s * 1000)).format('hh:mm:ss')
    }

    //引入office_efficiency_data.js缓存假数据
    if (data.code == 0) {
        $(".no-data").remove();
        loadData()
        //加载门店基本信息
        // loadChannelBaseInfo();
        //加载请求详情
        const nowTime = new Date()
        let timeList = [
            getTime(nowTime, 9),
            getTime(nowTime, 8),
            getTime(nowTime, 7),
            getTime(nowTime, 6),
            getTime(nowTime, 5),
            getTime(nowTime, 4),
            getTime(nowTime, 3),
            getTime(nowTime, 2),
            getTime(nowTime, 1),
            nowTime.format('hh:mm:ss')
        ]
        let total = new Array(10).fill(0)
        let normal = new Array(10).fill(0)
        let anomalous = new Array(10).fill(0)
        setInterval(() => {
            fetch('/get_requests')
                .then(res => res.json())
                .then(res => {
                    total.shift()
                    normal.shift()
                    anomalous.shift()
                    timeList.shift()

                    total.push(res.Total)
                    normal.push(res.Normal)
                    anomalous.push(res.Anomalous)
                    timeList.push(new Date().format('hh:mm:ss'))

                    const data = {
                        total,
                        normal,
                        anomalous
                    }
                    loadChannelHandleDetail(data, timeList);
                })
        }, 1000)
        // //加载营业员受理详情
        // loadStaffHandleDetail(data.staffHandleInfo);
        // //加载门店台席健康度详情
        // loadChannelDeviceDetail(data.channelDeviceInfo);
        // //加载业务类型耗时详情
        // loadBusinessTypeTimeDetail(data.businessTypeAnalysis);
    }

}

$(function () {
    //加载基础信息
    initBaseInfo();
    //加载页面数据
    loadPageData();
})